package com.pickgliss.ds
{
	import com.pickgliss.utils.ObjectUtils;

	public class ObjectPool
	{
		private var _class:Class;
		private var _freeItems:Array = [];
		private var _usedItems:Array = [];
		public function ObjectPool(clazz:Class)
		{
			_class = clazz;
			_freeItems = [];
			_usedItems = [];
			creatItems(3);
		}
		
		public function getItem():*
		{
			if(_freeItems.length == 0)creatItems(1);
			var freeItem:* = _freeItems.shift();
			_usedItems.push(freeItem);
			return freeItem;
		}
		
		public function freeItem(item:*):void
		{
			var index:int = _usedItems.indexOf(item);
			_usedItems.splice(index,1);
			_freeItems.push(item);
		}
		
		private function creatItems(count:int):void
		{
			for(var i:int = 0;i<count;i++)
			{
				_freeItems.push(new _class());
			}
		}
		
		public function clear():void
		{
			for(var i:int = 0;i<_freeItems.length;i++)
			{
				ObjectUtils.disposeObject(_freeItems[i]);
			}
			
			for(var j:int = 0;j<_freeItems.length;j++)
			{
				ObjectUtils.disposeObject(_freeItems[j]);
			}
			_freeItems = [];
			_usedItems = [];
		}
	}
}